package com.ddogring.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ddogring.alipay.config.AliPayConfig;
import com.ddogring.business.domain.Order;
import com.ddogring.business.domain.UnifiedPay;
import com.ddogring.business.service.IAliPayService;
import com.ddogring.business.service.IOrderService;
import com.ddogring.business.service.IUnifiedPayService;
import com.ddogring.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: eshop
 * @BelongsPackage: com.ddogring.business.service.impl
 * @Author: DdogRing
 * @CreateTime: 2023-02-02  14:02
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class AliPayServiceImpl implements IAliPayService {

    @Autowired
    private IUnifiedPayService unifiedPayService;

    /**
     * @description: 阿里支付
     * @author: DdogRing
     * @date: 2023/2/2 14:21
     * @param: []
     * @return: java.lang.String
     **/
    @Override
    public String aliPay(Map<String, Object> map) throws AlipayApiException {

        List<String> outTradeNos = (List<String>) map.get("outTradeNos");
        List<String> totalAmounts = (List<String>) map.get("totalAmount");

        UnifiedPay unifiedPay = null;
        String out_trade_no = IdUtils.fastSimpleUUID();

        for (int i = 0; i < outTradeNos.size(); i++) {
            unifiedPay = new UnifiedPay();
            unifiedPay.setUnifiedPay(out_trade_no);
            unifiedPay.setOrderId(outTradeNos.get(i));
            unifiedPay.setUserId(Integer.parseInt(map.get("userId").toString()));
            unifiedPay.setPayNum(new BigDecimal(totalAmounts.get(i)));
            unifiedPayService.save(unifiedPay);
        }

        BigDecimal total_amount = BigDecimal.ZERO;
        for (String totalAmount:totalAmounts) {
            BigDecimal bigDecimal = new BigDecimal(totalAmount);
            total_amount = total_amount.add(bigDecimal);
        }



        /*JSONObject bizContent = new JSONObject();
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount.toPlainString());
        bizContent.put("subject", map.get("subject") != null ? map.get("subject").toString() : "支付订单");
        System.out.println(bizContent.toString());*/

        return "/loan/toAlipay?out_trade_no=" + out_trade_no + "&total_amount=" + total_amount.toPlainString() + "&subject=" + (map.get("subject") != null ? map.get("subject").toString() : "支付订单");
    }
}
